//
//  ContactsViewController.m
//  Growth
//
//  Created by 洪波 陈 on 5/17/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "ContactsViewController.h"

#import "FriendInviteCellView.h"

#import "SelInviteViewController.h"
#import "RegexKitLite.h"

#define kSelInviteTitle @"手动输入"

@interface ContactsViewController ()

@end

@implementation ContactsViewController

@synthesize mytabelView;

@synthesize contactsDict;
@synthesize contactsArray;


- (void)dealloc
{
    [mytabelView release];
    //CLog(@"contactsDict count %d", [contactsDict retainCount]);
    [contactsDict release];
    //CLog(@"contactsArray count %d", [contactsArray retainCount]);
    [contactsArray release];
    
//    [handleButton release];
//    CLog(@"ContactsView released!");
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //定义返回按钮
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationController setNavigationBarHidden:YES];
//    UIBarButtonItem * backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: @"返回" style:UIBarButtonSystemItemDone target:self action: nil];   
//    
//    [[self navigationItem] setBackBarButtonItem:backBarButtonItem];  
//    [backBarButtonItem release];
//    
//    self.navigationItem.title = @"联系人";

    [self showPeoplePickerController];
    //[self loadContactData];
    [LoadingView hideWithAnimated:YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



#pragma mark Show all contacts
// Called when users tap "Display Picker" in the application. Displays a list of contacts and allows users to select a contact from that list.
// The application only shows the phone, email, and birthdate information of the selected contact.
-(void)showPeoplePickerController
{
	ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;
	// Display only a person's phone, email, and birthdate
	NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty], 
                               [NSNumber numberWithInt:kABPersonEmailProperty],
                               [NSNumber numberWithInt:kABPersonBirthdayProperty], nil];
	
	
	picker.displayedProperties = displayedItems;
	// Show the picker 
	//[self presentModalViewController:picker animated:YES];
    //[picker release];	
    [self.view addSubview:picker.view];
    
    
}


#pragma mark ABPeoplePickerNavigationControllerDelegate methods
// Displays the information of a selected person
static int selPersonPhonesCount = 0;
static int selPersonEmailsCount = 0;
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    CLog(@"person %@", person);

    CFTypeRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFTypeRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
    
    //电话
    NSMutableArray *phonsArray = [[NSMutableArray alloc] init];
    if(phones){
		//得到有多少个值
		int count =  ABMultiValueGetCount(phones);	
		
		//遍历取出值
		for(CFIndex i = 0;i<count;i++){
            
			NSString *phone = (NSString *)ABMultiValueCopyValueAtIndex(phones, i);
			CLog(@"phone:%@",phone);
            
            [phonsArray addObject:phone];
            [phone release];
            
		}
	}
    
    
    //邮件
    NSMutableArray *emailsArray = [[NSMutableArray alloc] init];
    if(emails){
		//得到有多少个值
		int count =  ABMultiValueGetCount(emails);	
		
		//遍历取出值
		for(CFIndex i = 0;i<count;i++){
            
			NSString *email = (NSString *)ABMultiValueCopyValueAtIndex(emails, i);
			CLog(@"email:%@",email);
            
            [emailsArray addObject:email];
            [email release];
            
		}
	}
    
    
    UIActionSheet *inviteAlert;
    if ([phonsArray count] == 0 && [emailsArray count] == 0) {
        inviteAlert = [[UIActionSheet alloc] initWithTitle:@"对不起，没有该好友的联系方式！" 
                                                  delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
        [inviteAlert addButtonWithTitle:kSelInviteTitle];
    }
    else {
        inviteAlert = [[UIActionSheet alloc] initWithTitle:@"选择您邀请好友的方式吧！" 
                                                  delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
        //Phone
        selPersonPhonesCount = [phonsArray count];
        for (NSString *str in phonsArray) {
            [inviteAlert addButtonWithTitle:str];
        }
        //Email
        selPersonEmailsCount = [emailsArray count];
        for (NSString *str in emailsArray) {
            [inviteAlert addButtonWithTitle:str];
        }
        
    }
    
    [inviteAlert addButtonWithTitle:@"取消"];
    [inviteAlert setCancelButtonIndex:[inviteAlert numberOfButtons]-1];
    
	// use the same style as the nav bar
	inviteAlert.actionSheetStyle = (UIActionSheetStyle)self.navigationController.navigationBar.barStyle;
	
	[inviteAlert showInView:self.view];
	[inviteAlert release];
    
    
	return NO;
}


// Does not allow users to perform default actions such as dialing a phone number, when they select a person property.
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person 
								property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
	return NO;
}


// Dismisses the people picker and shows the application when users tap Cancel. 
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker;
{
    [self.navigationController setNavigationBarHidden:NO];
	[self dismissModalViewControllerAnimated:NO];
    [self.navigationController popViewControllerAnimated:YES];
}




#pragma mark -
#pragma mark 加载数据
- (void)loadContactData
{
    if (contactsDict == nil) {
        contactsDict = [[NSMutableDictionary alloc] init];
    }
    
    if (contactsArray == nil) {
        contactsArray = [[NSMutableArray alloc] init];
    }
    
    
    
    ABAddressBookRef addressBook=ABAddressBookCreate();
    
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople (addressBook);
    
    CFArrayRef allGroups = ABAddressBookCopyArrayOfAllGroups(addressBook);
    
    for (id person in (NSArray *) allPeople)
        [self logContact:person];
    
//    for (id group in (NSArray *) allGroups)
//        [self logGroup:group];

    
    CFRelease(allGroups);
    
    CFRelease(allPeople);
    
    CFRelease(addressBook);
}

//得到联系人
-(void)logContact:(id)person{
    NSString *name = (NSString *)ABRecordCopyCompositeName(person);
    
    if (name == nil) {
        return;
    }
    
    ABRecordID recId = ABRecordGetRecordID(person);
    CLog(@"Person Name: %@ RecordID:%d",name, recId);
    CFTypeRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFTypeRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
    
    CFDataRef dataRef = ABPersonCopyImageData(person);
    
    UIImage *image = [UIImage imageWithData:(NSData *)dataRef];//这个就是我们要获取的Image的值
    
    //电话
    NSMutableArray *phonsArray = [[NSMutableArray alloc] init];
    if(phones){
		//得到有多少个值
		int count =  ABMultiValueGetCount(phones);	
		
		//遍历取出值
		for(CFIndex i = 0;i<count;i++){
            
			NSString *phone = (NSString *)ABMultiValueCopyValueAtIndex(phones, i);
			CLog(@"phone:%@",phone);
            
            [phonsArray addObject:phone];
            [phone release];

		}
	}
    
    
    //邮件
    NSMutableArray *emailsArray = [[NSMutableArray alloc] init];
    if(emails){
		//得到有多少个值
		int count =  ABMultiValueGetCount(emails);	
		
		//遍历取出值
		for(CFIndex i = 0;i<count;i++){
            
			NSString *email = (NSString *)ABMultiValueCopyValueAtIndex(emails, i);
			CLog(@"email:%@",email);
            
            [emailsArray addObject:email];
            [email release];

		}
	}
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    
    [dict setObject:name forKey:@"name"];
    [dict setObject:phonsArray forKey:@"phones"];
    [dict setObject:emailsArray forKey:@"emails"];
    
    [phonsArray release];
    [emailsArray release];
    
    if (image != nil) {
        [dict setObject:image forKey:@"image"];
        
        //CLog(@"image count %d", [image retainCount]);
    }
    
    
    NSDictionary *personDict = [[NSDictionary alloc] initWithDictionary:dict];
    [contactsArray addObject:personDict];
    [personDict release];
    //CLog(@"person dict count %d", [personDict retainCount]);

    [dict release];
    
}
//得到分组
-(void)logGroup:(id)group{
    CFStringRef name = ABRecordCopyValue(group,kABGroupNameProperty);
    ABRecordID recId = ABRecordGetRecordID(group);
    
    CLog(@"Group Name: %@ RecordID:%d",name, recId);
}
-(IBAction)beforBackHome:(id)sender{
    [self.view removeFromSuperview];
}

#pragma mark -
#pragma mark TableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [contactsArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    if (contactsArray == nil || row > [contactsArray count]) {
        return nil;
    }
    
    static NSString *MyIdentifier = @"FriendInviteCellView";
	// Try to retrieve from the table view a now-unused cell with the given identifier.
	FriendInviteCellView *cell =(FriendInviteCellView *) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
	
    if (cell == nil) {
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FriendInviteCellView" 
                                                     owner:self options:nil];
#ifdef __IPHONE_2_1
		cell = (FriendInviteCellView *)[nib objectAtIndex:0];
#else
		cell = (FriendInviteCellView *)[nib objectAtIndex:1];
#endif
    
//    static NSString *CellIdentifier = @"Cell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    if (cell == nil) {
//        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
//		cell.textLabel.font = [cell.textLabel.font fontWithSize:14];
        
        cell.imageView.layer.cornerRadius =3;
        cell.imageView.clipsToBounds = YES;
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(250, 9, 50, 25)];
        [button addTarget:self action:@selector(inviteFirendAction:) forControlEvents:UIControlEventTouchUpInside];
        [button setBackgroundImage:[UIImage imageNamed:@"button1bg_friend1_iphone.png"] forState:UIControlStateNormal];
        button.tag = row;
        
        
        UILabel *addLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(button.frame), CGRectGetHeight(button.frame))];
        [addLabel setTextAlignment:UITextAlignmentCenter];
        [addLabel setFont:[UIFont systemFontOfSize:14]];
        [addLabel setText:@"邀请"];
        addLabel.tag = 110;
        addLabel.font = [UIFont boldSystemFontOfSize:14];
        [addLabel setBackgroundColor:[UIColor clearColor]];
        [button addSubview:addLabel];
        
        [cell addSubview:button];
        [button release];
        
        [addLabel release];
    }
    

    
    NSDictionary *dict = [contactsArray objectAtIndex:row];
    
    cell.titleLabel.text = [dict objectForKey:@"name"];
    
    UIImage *image = [dict objectForKey:@"image"];
    if (cell.imageView) {
        if (image) {
            cell.imageView.image = image;
        }
        else {
            cell.imageView.image = [UIImage imageNamed:@"bg_imageView.png"];
        }

    }
   	
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setSelected:NO];
    
	return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 40;
    
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
	return cell.frame.size.height;

}

//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    
//    return 50;
//}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    NSInteger row = indexPath.row;
//    
//    selectIndex = row;
//    
//    NSDictionary *dict = [contactsArray objectAtIndex:row];
//    
//    NSString *str = [dict objectForKey:@"name"];
//    CLog(@"Sel people name %@", str); 
//    
//    NSArray *phones = [dict objectForKey:@"phones"];
//    NSArray *emails = [dict objectForKey:@"emails"];
//    
//    UIActionSheet *inviteAlert;
//    if ([phones count] == 0 && [emails count] == 0) {
//        inviteAlert = [[UIActionSheet alloc] initWithTitle:@"对不起，没有该好友的联系方式！" 
//                                                                 delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
//        [inviteAlert addButtonWithTitle:kSelInviteTitle];
//    }
//    else {
//        inviteAlert = [[UIActionSheet alloc] initWithTitle:@"选择您邀请好友的方式吧！" 
//                                                                 delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
//        //Phone
//        for (NSString *str in phones) {
//            [inviteAlert addButtonWithTitle:str];
//        }
//        //Email
//        for (NSString *str in emails) {
//            [inviteAlert addButtonWithTitle:str];
//        }
//    }
//
//    [inviteAlert addButtonWithTitle:@"取消"];
//    [inviteAlert setCancelButtonIndex:[inviteAlert numberOfButtons]-1];
//    
//	// use the same style as the nav bar
//	inviteAlert.actionSheetStyle = (UIActionSheetStyle)self.navigationController.navigationBar.barStyle;
//	
//	[inviteAlert showInView:self.view];
//	[inviteAlert release];
}

#pragma mark -
#pragma mark Action 
- (void)inviteFirendAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSInteger row = button.tag;
    
    [button setSelected:YES];
    
    handleButton = button;
    selectIndex = row;
    
    NSDictionary *dict = [contactsArray objectAtIndex:row];
    
    NSString *str = [dict objectForKey:@"name"];
    CLog(@"Sel people name %@", str); 
    
    NSArray *phones = [dict objectForKey:@"phones"];
    NSArray *emails = [dict objectForKey:@"emails"];
    
    UIActionSheet *inviteAlert;
    if ([phones count] == 0 && [emails count] == 0) {
        inviteAlert = [[UIActionSheet alloc] initWithTitle:@"对不起，没有该好友的联系方式！" 
                                                  delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
        [inviteAlert addButtonWithTitle:kSelInviteTitle];
    }
    else {
        inviteAlert = [[UIActionSheet alloc] initWithTitle:@"选择您邀请好友的方式吧！" 
                                                  delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
        //Phone
        for (NSString *str in phones) {
            [inviteAlert addButtonWithTitle:str];
        }
        //Email
        for (NSString *str in emails) {
            [inviteAlert addButtonWithTitle:str];
        }
        
        inviteAlert.tag = row;
        
    }
    
    [inviteAlert addButtonWithTitle:@"取消"];
    [inviteAlert setCancelButtonIndex:[inviteAlert numberOfButtons]-1];
    
	// use the same style as the nav bar
	inviteAlert.actionSheetStyle = (UIActionSheetStyle)self.navigationController.navigationBar.barStyle;
	
	[inviteAlert showInView:self.view];
	[inviteAlert release];
}

#pragma mark -
#pragma mark UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)modalView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // Change the navigation bar style, also make the status bar match with it
    
    NSString *str = [modalView buttonTitleAtIndex:buttonIndex];
    
    CLog(@"Sel person phonesCount %d button index %d", selPersonPhonesCount, buttonIndex);
    
    if ([str isEqualToString:kSelInviteTitle]) {
        SelInviteViewController *content = [[SelInviteViewController alloc] init];
        
        [self.navigationController pushViewController:content animated:YES];
        [content release];
        
        CLog(@"自定义短信/邮件");
    }

    if (buttonIndex < selPersonPhonesCount) {
         [self sendSMSWith:str];
    }
    else {
        if (buttonIndex <selPersonEmailsCount +selPersonPhonesCount) {
            [self sendEmailWith:str];
        }
         
    }
    
    CLog(@"User sel %@", str);
}


- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    CLog(@"didDismissWithButtonIndex");
    
}


//- (void)actionSheet:(UIActionSheet *)modalView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    // Change the navigation bar style, also make the status bar match with it
//    
//    NSString *str = [modalView buttonTitleAtIndex:buttonIndex];
//    
//    if ([str isEqualToString:kSelInviteTitle]) {
//        SelInviteViewController *content = [[SelInviteViewController alloc] init];
//        
//        [self.navigationController pushViewController:content animated:YES];
//        [content release];
//        
//        CLog(@"自定义短信/邮件");
//    }
//
//    NSInteger index = modalView.tag;
//    
//    NSDictionary *dict = [contactsArray objectAtIndex:index];
//    
//    NSArray *phones = [dict objectForKey:@"phones"];
//    NSArray *emails = [dict objectForKey:@"emails"];
//    
//    if (buttonIndex <[phones count]) {
//        [self sendSMSWith:str];
//    }
//    else if(buttonIndex < [phones count] + [emails count]){
//        [self sendEmailWith:str];
//    }
//    
//    [handleButton setSelected:YES];
//    [handleButton isHighlighted];
//    
//    
//    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:selectIndex inSection:0];
//    FriendInviteCellView *cell = (FriendInviteCellView *)[self tableView:mytabelView cellForRowAtIndexPath:indexPath];
//    
//    [cell.actionButton setHidden:YES];
//    [cell.tipsImageView setHidden:NO];
//    
//    [cell selected];
//    
//    CLog(@"User sel %@", str);
//}


#pragma mark -
#pragma mark Compose Mail/SMS


- (void)sendSMSWith:(NSString *)phoneNumStr
{
    Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
	
	if (messageClass != nil) { 			
		// Check whether the current device is configured for sending SMS messages
		if ([messageClass canSendText]) {
			[self displaySMSComposerSheetWith:phoneNumStr];
		}
		else {	
			[LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"您的设备不支持发短信哦！" duration:DEFAULT_LOADING_TIME];
            
		}
	}
	else {
		[LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"您的设备不支持发短信哦！" duration:DEFAULT_LOADING_TIME];
	}
}


- (void)sendEmailWith:(NSString *)email
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    
	if (mailClass != nil) {
        //[self displayMailComposerSheet];
		// We must always check whether the current device is configured for sending emails

        if ([mailClass canSendMail]) {
			[self displayMailComposerSheetWith:email];
		}
		else {
			[self launchMailAppOnDeviceWith:email];
		}
	}
	else	{
		[LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"您的设备不能发邮件哦！" duration:DEFAULT_LOADING_TIME];
	}
}

// Displays an email composition interface inside the application. Populates all the Mail fields. 
-(void)displayMailComposerSheetWith:(NSString *)emailStr 
{
    [self dismissModalViewControllerAnimated:NO];
    
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	
	[picker setSubject:@"我正在使用印象宝贝"];
	
	
	// Set up recipients
	NSArray *toRecipients = [NSArray arrayWithObject:emailStr]; 
	
	[picker setToRecipients:toRecipients];
	
	// Attach an image to the email
    //	NSString *path = [[NSBundle mainBundle] pathForResource:@"rainy" ofType:@"jpg"];
    //	NSData *myData = [NSData dataWithContentsOfFile:path];
    //	[picker addAttachmentData:myData mimeType:@"image/jpeg" fileName:@"rainy"];
	
	// Fill out the email body text
    NSString *userNickName = [[NSUserDefaults standardUserDefaults] valueForKey:@"userName"];
    NSString *bodyStr = [NSString stringWithFormat:@"我正在使用印象宝贝，如果你通过http://www.lanbaoo.com/app/download  下载，就可以和我一起分享宝宝的成长啦。记得加我为好友哦，我的昵称是%@。【印象宝贝——移动互联时代儿童成长亲密助手】",userNickName ];
	[picker setMessageBody:bodyStr isHTML:NO];
	
	[self presentModalViewController:picker animated:YES];
   
	[picker release];
}

// Launches the Mail application on the device.
-(void)launchMailAppOnDeviceWith:(NSString *)emailStr
{
    NSString *userNickName = [[NSUserDefaults standardUserDefaults] valueForKey:@"userName"];
    NSString *bodyStr = [NSString stringWithFormat:@"我正在使用印象宝贝， 如果你通过http://www.lanbaoo.com/app/download 下载，就可以和我一起记录并分享宝宝的精彩瞬间啦。记得加我为好友哦，我的昵称是%@。 【印象宝贝——移动互联时代儿童成长亲密助手】",userNickName ];
    
	NSString *recipients = [NSString stringWithFormat:@"mailto:%@?subject=我正在使用印象宝贝", emailStr] ;
	NSString *body = [NSString stringWithFormat:@"&body=%@", bodyStr] ;
    
	
	NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
	email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}

// Displays an SMS composition interface inside the application. 
-(void)displaySMSComposerSheetWith:(NSString *)phoneNumStr 
{
    [self dismissModalViewControllerAnimated:NO];
    
	MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
    
    NSArray *phoneArray = [NSArray arrayWithObjects:phoneNumStr, nil];
    
    [picker setRecipients:phoneArray];
    NSString *userNickName = [[NSUserDefaults standardUserDefaults] valueForKey:@"userName"];
    NSString *bodyStr = [NSString stringWithFormat:@"我正在使用印象宝贝，如果你通过http://www.lanbaoo.com/app/download  下载，就可以和我一起分享宝宝的成长啦。记得加我为好友哦，我的昵称是%@。【印象宝贝——移动互联时代儿童成长亲密助手】",userNickName ];
    [picker setBody:bodyStr ];
    
	picker.messageComposeDelegate = self;
	
	[self presentModalViewController:picker animated:YES];
	[picker release];
}
#pragma mark -
#pragma mark Dismiss Mail/SMS view controller
// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the 
// message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller 
          didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    
    
	// Notifies users about errors associated with the interface
    
	switch (result)
	{
		case MFMailComposeResultCancelled:
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME /2 message:@"邮件已取消"];
			break;
		case MFMailComposeResultSaved:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME /2 message:@"邮件已保存"];
			break;
		case MFMailComposeResultSent:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME /2 message:@"邮件已发送"];
			break;
		case MFMailComposeResultFailed:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME /2 message:@"邮件发送失败"];
			break;
		default:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME /2 message:@"邮件发送失败"];
			break;
	}
    
    [controller dismissModalViewControllerAnimated:YES];
}

// Dismisses the message composition interface when users tap Cancel or Send. Proceeds to update the 
// feedback message field with the result of the operation.
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller 
                 didFinishWithResult:(MessageComposeResult)result {
    
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MessageComposeResultCancelled:
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME /2 message:@"短信已取消"];
			break;
		case MessageComposeResultSent:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME /2 message:@"短信已发送"];
			break;
		case MessageComposeResultFailed:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME /2 message:@"短信发送失败"];
			break;
		default:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME /2 message:@"短信发送失败"];
			break;
	}
	[self dismissModalViewControllerAnimated:YES];
}






@end
